// pages/course/offlineCourse/detail/detail.js
const common = require('../../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navType: 1,
        courseId: null,
        courseInfo: {},
        commentList: [],
        nowPage: 0,
        isLoading: false,
        isAll: false,
        isBuyIng: false,
        ewmCode: '',
        applyInfoShow: false,
        applyInfoName: '',
        applyInfoPhone: '',
        applyInfoWX: '',
        applyInfoInviter: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.userShare) {
            wx.setStorageSync('userShare', options.userShare)
            let data = {
                belong_refer: options.userShare
            }
            common.post('User/set_belong_refer', data).then(function(res) {}).catch(function(e) {})
        }
        this.setData({
            courseId: options.courseId
        })
        this.getCourseInfo()
        this.getSystemInfo()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.setData({
            commentList: [],
            nowPage: 0,
            isLoading: false,
            isAll: false
        })
        this.getCommentList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (this.data.navType == 2) {
            this.getCommentList()
        }
    },

    onShareAppMessage: function(res) {
        const that = this
        let userId = wx.getStorageSync('userId')
        console.log(userId)
        return {
            title: that.data.courseInfo.name,
            path: '/pages/course/offlineCourse/detail/detail?courseId=' + that.data.courseId + '&userShare=' + userId,
            imageUrl: that.data.courseInfo.background
        }
    },

    getSystemInfo: function() {
        const that = this
        wx.getSystemInfo({
            success(res) {
                that.setData({
                    statusBarHeight: res.statusBarHeight + 5
                })
            }
        })
    },

    navClick: function(e) {
        if (e.currentTarget.dataset.type == this.data.navType) {
            return
        }
        this.setData({
            navType: e.currentTarget.dataset.type
        })
    },

    getCourseInfo: function() {
        wx.showLoading({
            title: '加载中',
        })
        const that = this
        let data = {
            activity: 785,
            online_id: this.data.courseId,
            paramter: 1
        }
        common.post('Online/down_online_list', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                that.setData({
                    courseInfo: {},
                })
            } else {
                res[0].image_info = res[0].image_info.replace(/\<img/gi, '<img style="display:block;width:100%;height:auto" ')
                that.setData({
                    courseInfo: res[0]
                })
                that.getCommentList()
            }
        }).catch(function(e) {})
    },

    getEwmCode: function() {
        const that = this
        let data = {
            online_id: this.data.courseId
        }
        common.post('Qrcodes/create_online_down', data).then(function(res) {
            that.setData({
                ewmCode: res
            })
            that.setData({
                showShareImg: true
            })
            that.createImg()
        }).catch(function(e) {})
    },

    getCommentList: function() {
        if (this.data.isLoading) {
            return
        }
        if (this.data.isAll) {
            return
        }
        const that = this
        let commentList = this.data.commentList
        let data = {
            activity: 785,
            online_id: this.data.courseId,
            page: this.data.nowPage,
            limit: 10
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '加载中',
        })
        common.post('Online/online_comment', data).then(function(res) {
            that.setData({
                isLoading: false
            })
            wx.hideLoading()
            if (res.code == 204) {
                that.setData({
                    commentList: commentList,
                    isAll: true
                })
            } else {
                commentList = commentList.concat(res)
                that.setData({
                    commentList: commentList,
                    nowPage: that.data.nowPage + 1
                })
            }
        }).catch(function(e) {})
    },

    goApply: function() {
        if (this.data.courseInfo.is_buy == 1) {
            wx.showToast({
                title: '您已成功报名，请勿重复报名',
                icon: 'none',
                duration: 1000
            })
            return
        }
        this.setData({
            applyInfoShow: true
        })
    },

    goBuy: function(e) {
        if (this.data.isBuyIng) {
            return
        }
        if (this.data.applyInfoName == '') {
            wx.showToast({
                title: '请填写姓名',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.applyInfoPhone == '') {
            wx.showToast({
                title: '请填写联系电话',
                icon: 'none',
                duration: 2000
            })
            return
        }
        wx.showLoading({
            title: '请稍后'
        })
        this.setData({
            isBuyIng: true
        })
        const that = this
        wx.login({
            success(res) {
                if (res.code) {
                    wx.setStorageSync('code', res.code)
                    //发起网络请求
                    let data = {
                        online_id: e.currentTarget.dataset.id,
                        name: that.data.applyInfoName,
                        phone: that.data.applyInfoPhone,
                        wx_id: that.data.applyInfoWX,
                        parent_id: that.data.applyInfoInviter,
                        code: res.code,
                        pay_client: 1
                    }
                    common.post('Order/order_buy_online', data).then(function(res) {
                        wx.hideLoading()
                        wx.login({
                            success(res) {
                                wx.setStorageSync('code', res.code)
                            }
                        })
                        that.setData({
                            isBuyIng: false
                        })
                        if (res.code == 204) {
                            wx.showToast({
                                title: res.error,
                                icon: 'none',
                                duration: 2000
                            })
                        } else {
                            wx.requestPayment({
                                timeStamp: res.timeStamp,
                                nonceStr: res.nonceStr,
                                package: res.package,
                                signType: res.signType,
                                paySign: res.paySign,
                                success(res) {
                                    wx.showModal({
                                        title: '提示',
                                        content: '报名成功',
                                        showCancel: false,
                                        success(res) {
                                            if (res.confirm) {
                                                wx.redirectTo({
                                                    url: '/pages/course/offlineCourse/applyList/applyList?navType=2'
                                                })
                                            }
                                        }
                                    })

                                },
                                fail(res) {
                                    wx.showToast({
                                        title: '支付失败',
                                        icon: 'none',
                                        duration: 2000
                                    })
                                }
                            })
                        }
                    }).catch(function(e) {})
                }
            }
        })
    },

    myCatchTouch: function() {
        return
    },

    share: function() {
        this.getEwmCode()
    },

    closeShare: function() {
        this.setData({
            showShareImg: false
        })
    },
    createImg: function() {
        wx.showLoading({
            title: '正在生成图片...',
        })
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: 'https:' + that.data.courseInfo.background.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.courseInfo.teacher.teacher_head.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.ewmCode.split(':')[1]
            })
        ]).then(res => {
            const ctx = wx.createCanvasContext('shareCanvas')
            ctx.rect(0, 0, 750, 1234)
            ctx.setFillStyle('white')
            ctx.fill()
            ctx.drawImage(res[0].path, 0, 0, 750, 580)
            ctx.drawImage(res[2].path, 50, 970, 230, 230)
            this.circleImg(ctx, res[1].path, 50, 620, 60)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(30)
            ctx.fillText(that.data.courseInfo.teacher.teacher_name, 200, 690)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(36)
            ctx.fillText(that.data.courseInfo.name.slice(0, 18), 50, 800)
            ctx.setFillStyle('#666666')
            ctx.setFontSize(32)
            ctx.fillText(that.data.courseInfo.birfte.slice(0, 21), 50, 870)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(28)
            if (that.data.courseInfo.birfte.length > 20) {
                ctx.setFillStyle('#666666')
                ctx.setFontSize(32)
                ctx.fillText(that.data.courseInfo.birfte.slice(21, 41) + '...', 50, 920)
            }
            ctx.setFillStyle('#131313')
            ctx.setFontSize(28)
            ctx.fillText('长按识别二维码进入课程', 320, 1060)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(28)
            ctx.fillText('财大师', 320, 1110)
            ctx.draw(false, function(e) {
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                wxCanvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1234,
                    destWidth: 750,
                    destHeight: 1234
                }, this).then(res => {
                    wx.hideLoading()
                    that.setData({
                        previewImg: res.tempFilePath
                    })
                })
            })
        })
    },

    downloadImg: function() {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: this.data.previewImg,
            success: function(data) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
                that.closeShare()
            },
            fail: function(err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '用户未授权',
                        content: '请先开启保存到相册权限，开启后即可保存图片',
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            wx.saveImageToPhotosAlbum({
                                                filePath: that.data.previewImg,
                                                success(res) {
                                                    wx.showToast({
                                                        title: '保存成功',
                                                        icon: 'success',
                                                        duration: 2000
                                                    })
                                                    that.closeShare()
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            } else if (res.cancel) {
                                wx.showToast({
                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        }
                    })
                }
            }
        })
    },

    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function(ctx, img, x, y, r) {
        ctx.beginPath()
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    closeApplyInfo: function() {
        this.setData({
            applyInfoShow: false
        })
    },

    applyInfoNameInput: function(e) {
        this.setData({
            applyInfoName: e.detail.value
        })
    },

    applyInfoPhoneInput: function(e) {
        this.setData({
            applyInfoPhone: e.detail.value
        })
    },

    applyInfoWXInput: function(e) {
        this.setData({
            applyInfoWX: e.detail.value
        })
    },

    applyInfoInviterInput: function(e) {
        this.setData({
            applyInfoInviter: e.detail.value
        })
    }
})